<template>
  <view
    v-show="isActive"
    class="fu-tab"
    :class="{
      'fu-tab--active': isActive,
      'fu-tab--animated': parent && parent.animated
    }"
    :style="style"
  >
    <slot></slot>
  </view>
</template>

<script>
/**
 * fu-tab 标签页面板组件
 * @description 标签页面板，用于展示标签页的内容，需要和fu-tabs配合使用
 * @property {String/Number} name - 标签名称，作为匹配的标识符
 * @property {String} title - 标题
 * @property {Boolean} disabled - 是否禁用
 */
export default {
  name: 'fu-tab',
  props: {
    name: {
      type: [String, Number],
      default: null
    },
    title: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      parent: null,
      index: null,
      inited: false
    }
  },
  computed: {
    isActive() {
      if (!this.parent) return false
      const active = this.parent.currentName === this.computedName
      if (active && !this.inited) {
        this.inited = true
      }
      return active
    },
    computedName() {
      return this.name ?? this.index
    },
    style() {
      if (!this.parent || !this.parent.animated) return {}
      
      const index = this.parent.children.findIndex(item => item.computedName === this.parent.currentName)
      const distance = this.index - index
      const translate = distance * 100
      
      return {
        transform: `translateX(${translate}%)`,
        webkitTransform: `translateX(${translate}%)`
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      let parent = this.$parent
      while (parent && parent.$options.name !== 'fu-tabs') {
        parent = parent.$parent
      }
      if (parent) {
        this.parent = parent
        this.index = this.parent.children.length
        this.parent.addChild(this)
      }
    },
    beforeDestroy() {
      if (this.parent) {
        this.parent.removeChild(this)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.fu-tab {
  &--animated {
    position: absolute;
    left: 0;
    right: 0;
    height: 100%;
    transition: transform 0.3s;
  }
  
  &--active {
    position: relative;
    z-index: 1;
  }
}
</style> 